package com.zac.coroutine.algorithm.leetcode.others

/**
 * author zac
 * date 2024/10/12
 * --简单--
 *给你两个二进制字符串 a 和 b ，以二进制字符串的形式返回它们的和。
 *
 *
 *
 * 示例 1：
 *
 * 输入:a = "11", b = "1"
 * 输出："100"
 * 示例 2：
 *
 * 输入：a = "1010", b = "1011"
 * 输出："10101"
 *
 *
 * 提示：
 *
 * 1 <= a.length, b.length <= 104
 * a 和 b 仅由字符 '0' 或 '1' 组成
 * 字符串如果不是 "0" ，就不含前导零
 */
class Test4 {


    companion object {

        @JvmStatic
        fun main(args: Array<String>) {
            add("11", "1")
        }


        fun add1(a:String,b: String){
            if (a.length > b.length){

            }
        }

        fun add(a: String, b: String): String {
            val length = if (a.length > b.length) a.length else b.length
            val result = StringBuilder()
            var front = 0
            for (i in length - 1 downTo 0) {
                if (i < a.length && i < b.length) {
                    val sum = a[i].digitToInt() + b[i].digitToInt() + front
                    val digit = when (sum) {
                        0 -> {
                            front = 0
                            0
                        }

                        1 -> {
                            front = 0
                            1
                        }

                        2 -> {
                            front = 1
                            0
                        }

                        else -> {
                            front = 1
                            1
                        }

                    }
                    result.insert(0, digit)
                    println("i = $i, result = $result,front = $front")
                } else {
                    val digit = if (i >= a.length) {
                        front + b[i].digitToInt()
                    } else {
                        front + a[i].digitToInt()
                    }
                    when (digit) {
                        0 -> {
                            result.insert(0, digit)
                        }

                        1 -> {
                            result.insert(0, digit)
                        }

                        else -> {
                            result.insert(0, "10")
                        }
                    }
                    println("i = $i, result = $result,front = $front")
                }


            }
            if (front != 0) {
                result.insert(0, 1)
            }
            println("final result = $result")
            return result.toString()

        }
    }


}